//
//  ZHomeDataDao.swift
//  swift-weibo
//
//  Created by zero on 17/4/2.
//  Copyright © 2017年 zero. All rights reserved.
//

import UIKit

class ZHomeDataDao: NSObject {

    
    
}

//MARK:检查本地是否有
extension ZHomeDataDao{
    
    class func checkData(since_id: Int64, max_id: Int64, finished:@escaping (Any?)->()){
        
        //  先从本地读取
        let tempArray = readData(since_id: since_id, max_id: max_id)
        
        //  判断
        if tempArray.count > 0 {
            
            print("本地有数据")
            
            finished(tempArray)
            
            return
        }
        
//          如果本地没有 那么就从网络获取
        ZNetworkTools.shared.homeLoadData(since_id: since_id, max_id: max_id) { (res, error) in
            
            if error != nil{
                
                print("ZHomeControllerViewModel请求错误")
                
                finished(nil)
                return
            }
            
            
            //  不为nil 并且是字典类型
            guard let response = res as? [String : Any] else{
                
                print("ZHomeControllerViewModel不为nil 并且是字典类型")
                
                finished(nil)
                return
            }
            
            guard let resArr = response["statuses"] as? [[String: Any]] else{
                
                print("ZHomeControllerViewModel获取数组失败")
                finished(nil)
                return
            }
            
            //  保存到本地
            if ZHomeDataDao.saveData(targetArray: resArr){
                print("保存数据成功")
            }else{
                print("保存数据失败")
            }
            
            finished(resArr)

        }
        
        
    }
}
//MARK:从本地读取
extension ZHomeDataDao{
    
    class func readData(since_id: Int64, max_id: Int64) ->[[String:Any]]{
        
        // 创建一个临时可变的数组
        var tempArray:[[String: Any]] = [[String: Any]]()
        
        //  获取用户id
        guard let uid = ZUserAccountViewModel.shareUserAccoutn.account?.uid else {
            
            print("uid")
            return tempArray
        }
        
        
        //  首次从网络获取
        if since_id == 0 && max_id == 0 {
            
            return tempArray
        }
        
        // 准备sql
        var sql = ""
        sql += "SELECT * FROM t_content "
        sql += "WHERE userid=\(uid) "
        
        if since_id > 0 {
            
            sql += "AND statusid>\(since_id) "
        }
        
        if max_id > 0 {
            
            sql += "AND statusid<=\(max_id) "
        }
        
        sql += "ORDER BY statusid DESC "
        sql += "LIMIT 20"
        //  从数据库读取
        let result = ZFMDBDao.share.selectedData(sqlString: sql)
        
        //  遍历数据
        for dic in result{
            
            //  获取对应的二进制
            let data = dic["statusContent"] as! Data
            
            //  二进制转化为字典
            let dict = try! JSONSerialization.jsonObject(with: data, options: [])
            
            tempArray.append(dict as! [String : Any])
        }
        
        return tempArray
    }
}
//MARK:保存在本地
extension ZHomeDataDao{
    
    class func saveData(targetArray:[[String:Any]]) -> Bool {
        
        //  获取用户id
        guard let uId = ZUserAccountViewModel.shareUserAccoutn.account?.uid else {
            
            print("ZHomeDataDao 获取用户的uid失败")
            return false
        }
        
        //  准备sql的语句VALUES
        let sqlString = "insert or replace into t_content (statusContent,statusId,userId) values(?,?,?)"
        
        ZFMDBDao.share.queue.inTransaction { (db, rollback) in
            
            for res in targetArray{
                
                let statusId = res["id"] as! Int64
                
                //  获取二进制数据
                let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                
                let res = db?.executeUpdate(sqlString, withArgumentsIn: [data,statusId,uId])
                
                if res! {
                    
                }else{
                    print("失败")
                    
                    rollback?.pointee = true
                }
            }
        }
        return true
    }
}
